package database;
import java.util.*;

public class Page {
	int number,sizemax,freeSpace,used,numberOfRecord;
	String tableName;
	Object[][] structure;
	Record[] content;
	
	public Page(){}
	
	public Page(Table table){
		used=0;
		numberOfRecord=0;
		content = new Record[1];
		sizemax=2000;
		freeSpace=2000;
		tableName= table.name;
		number = table.numberPages+1;
		table.numberPages++;
		structure = table.structure;
	}
	
	public Page(Table table, int pageNumber){
		used=0;
		numberOfRecord=0;
		content = new Record[1];
		sizemax=2000;
		freeSpace=2000;
		table.numberPages++;
		tableName= table.name;
		number = pageNumber;
		structure = table.structure;
	}
	
	public int size(){
		int i,size=0;
		for(i=0;i<numberOfRecord;i++){
			size += content[i].size();
		}
		return size;
	}
	
	public String addRecord(Record record){
		this.used++;
		Record[] contentTemp = new Record[numberOfRecord+1];
		int i;
		for(i=0 ; i < content.length ; i++){
			contentTemp[i] = content[i];
		}
		content = contentTemp;
		content[numberOfRecord] = record;
		String rid = number + "_" + numberOfRecord;
		this.numberOfRecord++;
		freeSpace -= record.size();
		return rid;
	}
	
	public Record getRecord(RecordID rid){
		this.used++;
		Record result = null;
		int i;
		for(i=0 ; i < content.length ; i++){
			if(content[i].rid.recordNumber == rid.recordNumber) 
				result = content[i];
		}
		
		return result;
	}
	
	public List<RecordID> searchRecord(String fieldName, Object fieldValue){
		this.used++;
		int i,j;
		int structIndex=-1;
		List<RecordID> returnList = new ArrayList<RecordID>();
		for(j=0 ; j < structure.length ; j++){
			if( fieldName.compareTo((String) structure[j][2]) == 0 ){
				structIndex = j;
			}
		}
		
		for(i=0 ; i < numberOfRecord ; i++){
			Record record = content[i];
			if( (fieldValue.toString()).compareTo(record.data[structIndex][1].toString()) == 0 ){				
				returnList.add(record.rid);																		////// IL Y A UN PROBLEME ICI CA STOQUE LE TOSTRING()
			}
		}
		return returnList;
	}
}